import React, { useState } from 'react'
import "@/assets/css/Email.scoped.css"

const Component = () =>
{
  //创建表单的对象结构
    const [form] = React.UI.Form.useForm()

    //初始化的个人资料数据
    let [business, SetBusiness] = useState({
        email: React.business.email,
        code: '',
    })

    //定义倒计时
    let [countdown,SetCountdown] = useState(0)

    // 发送状态
    let [isSending, SetIsSending] = useState(false);

    //发送验证码
    const send = async () => 
    { 
      // 如果正在发送中，则返回
      if(isSending) return

       // 禁止点击按钮
      SetIsSending(true)
      var params = {
        action: 'send',
        id:React.business.id
      }

      profile(params)

      //60秒倒计时
      SetCountdown(3)
      const time = setInterval(() => {
        SetCountdown((num) => {
          if(num <= 1)
          {
            clearInterval(time);
            SetIsSending(false)
            return 0
          }

          return num - 1
        })
      },1000)
    }

    //表单提交方法
    const profile = async (values:any) => 
    {
      var params = 
      {
        ...values,
        id:React.business.id
        // action: values.action ?? '',
        // code: values.vercode
      }
      // return false
      var result = await React.request.post('business/email', params)

      if(result.code == 0)
      {
        React.toast(result.msg, null, 'fail')
        return false
      }

      React.toast(result.msg, 'back', 'success')
      // React.toast('验证成功', 'back')
    }

  return (
    <>

      {/* 表单结构 */}
      <React.UI.Form
          style={{paddingTop: '10px'}}
          name="profile"
          layout='horizontal'
          mode='card'
          form={form}
          initialValues={business}
          onFinish={profile}
          footer={<React.UI.Button block type='submit' disabled={React.business.auth == 1 ? true : false} color='primary' size='large'>提交验证</React.UI.Button>}
      >
          <React.UI.Form.Item name="email" label="邮箱" style={{'--prefix-width': '4.5em'}} extra={<div style={{ pointerEvents: React.business.auth == 1 || countdown > 0 ? 'none' : 'auto'}} onClick={send}>{countdown > 0 ? <span>{countdown}秒后重试</span> : <a>发送验证码</a> }</div>}>
              <React.UI.Input placeholder="请输入邮箱" readOnly />
          </React.UI.Form.Item>

          <React.UI.Form.Item name="code" label="验证码" style={{'--prefix-width': '4.5em'}} rules={[{ required: true }]}>
              <React.UI.Input placeholder="请输入验证码" />
          </React.UI.Form.Item>
      </React.UI.Form>
    </>
  )
}

export default Component